package com.bdqn.intercept;


import com.bdqn.component.BlogConstants;
import com.bdqn.util.ResponseUtil;
import com.bdqn.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class CheckIntercept extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String accep = request.getHeader("Accept");
        boolean flag = false;
        if (StringUtils.isBlank(accep)){
            if (accep.startsWith("application/json") || accep.equals("*/*")){
                flag=true;
            }
        }

        Object obj = request.getSession().getAttribute(BlogConstants.LOGIN_SESSION_KEY);
        if (obj == null){
            if (flag){
                ResponseUtil.sendJson(response,Result.createError("登录已经失效，请重新登录"));
            }else {
                ResponseUtil.alertRedirect(response,"登录已经失效,请重新登录","/client/login.html");
            }
            return  false;
        }

        return true;
    }

}
